package onlinebanking.server.modules;

import onlinebanking.constants.MSG;
import onlinebanking.exceptions.UserNotLoggedInException;
import onlinebanking.network.Message;
import onlinebanking.server.ServerEngine;
import onlinebanking.server.objects.BankAccount;
import onlinebanking.server.objects.Session;

public class SelectActiveAccountModule extends Module {

	public SelectActiveAccountModule(ServerEngine se, Message message) {
		this.serverengine = se;
		this.message = message;

	}

	public Message handleRequest() {
		Message response;
		try {
			if (serverengine.isLoggedIn()) {

				Session session = serverengine.getSession();
				int personalaccountid = session.getUserAccount()
						.getpersonalaccountid();

				int requesttype = message.getMsgSubType();

				switch (requesttype) {

				case MSG.LIST_OF_BANKACCOUNTS:
					response = BankAccount.getBankAccounts(personalaccountid);
					break;

				case MSG.SELECT_ACTIVE_ACCOUNT:
					String accountno = message.getString("active_accountno");
					response = new Message();

					// TODO Add some verification that accountno belongs to the
					// active user
					if (!verifyOwner(accountno, personalaccountid)) {
						response.setMsgType(MSG.MY_BANK_ACCOUNTS);
						response.setMsgSubType(MSG.SELECT_ACTIVE_ACCOUNT);
						response.setSuccess(false);
						response.addAttribute("reason",
								"accountno does not belong to you");
						return response;
					}

					BankAccount currentBA = session.getActiveBankAccount();

					// if no active bankaccount
					if (currentBA == null) {

						BankAccount activeBA = new BankAccount(0,
								Integer.parseInt(accountno));
						session.setActiveBankAccount(activeBA);

					} else {
						// if the bankaccount is already active
						if (currentBA.getAccountno().equals(accountno)) {
							break;
						}

						// set new active bank account
						BankAccount activeBA = new BankAccount(0,
								Integer.parseInt(accountno));
						session.setActiveBankAccount(activeBA);
					}

					response.setMsgType(MSG.MY_BANK_ACCOUNTS);
					response.setMsgSubType(MSG.SELECT_ACTIVE_ACCOUNT);
					response.setSuccess(true);

					break;

				default:
					response = new Message();
					break;
				}

			} else {
				response = new Message();
				response.setAsUserNotLoggedIn();
			}
		} catch (UserNotLoggedInException e) {
			response = new Message();
			response.setAsUserNotLoggedIn();
		}
		return response;
	}

	/**
	 * 
	 * @param accountno
	 * @param personalaccountid
	 * @return true if valid owner
	 */
	private boolean verifyOwner(String accountno, int personalaccountid) {
		BankAccount ba = new BankAccount(0, Integer.parseInt(accountno));
		int bankaccountid = ba.getBankAccountID();
		return BankAccount.verifyOwnership(personalaccountid, bankaccountid);
	}

}
